package com.icss.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;


import com.icss.util.Constants;
import com.icss.helper.SpringHelper;

public class PermissionFilter implements Filter {



	public void setFilterConfig(FilterConfig config) {
		this.config = config;
	}

	public FilterConfig getFilterConfig() {
		return config;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpreq = (HttpServletRequest) request;
		HttpServletResponse httpres = (HttpServletResponse) response;

		String[] arrLogin = config.getInitParameter("loginStrings").split(";");
		String[] arrTest= config.getInitParameter("testStrings").split(";");
		String noSession = httpreq.getContextPath() + config.getInitParameter("noSession");
		String noPermission = httpreq.getContextPath() + config.getInitParameter("noPermission");
		String requestURI = httpreq.getRequestURI();
		Map user = (Map) httpreq.getSession().getAttribute("user");
		System.out.println("---------过滤器中user对象---------"+user);
		if (user == null) {
			if (!httpreq.getRequestURI().equals(Constants.WEBROOT) && !isContains(requestURI, arrLogin) ) {
				System.out.println("noSession! requestURI is :" + httpreq.getRequestURI());
				httpres.sendRedirect(noSession);
				return;
			}
		}  
		chain.doFilter(request, response);
	}

	public void destroy() {
		config = null;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
	}

	public FilterConfig config;


	public static boolean isContains(String container, String regx[]) {
		boolean result = false;
		for (int i = 0; i < regx.length; i++)
			if (container.indexOf(regx[i]) != -1)
				return true;

		return result;
	}
}
